/*******************************************************************************
 * Copyright (c) 2011 squid.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     squid - initial API and implementation
 ******************************************************************************/
package com.google.code.cubeirc;

import java.io.File;
import java.net.URL;
import java.util.Iterator;

import lombok.Getter;
import lombok.Setter;

import org.apache.log4j.Level;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import com.google.code.cubeirc.common.ApplicationInfo;
import com.google.code.cubeirc.common.HTTPClient;
import com.google.code.cubeirc.config.Configuration;
import com.google.code.cubeirc.debug.DebuggerQueue;
import com.google.code.cubeirc.dialogs.AlertBox;
import com.google.code.cubeirc.editor.TemplateManager;
import com.google.code.cubeirc.scripting.ScriptWatcher;
import com.google.code.cubeirc.sdk.CubePluginsHost;
import com.google.code.cubeirc.ui.MainForm;

public class Main {

	@Getter @Setter
	public static Shell shell;

	@Getter @Setter	
	public static ScriptWatcher scriptWatch;

	/**
	 * @param args
	 */
	public static void main(String[] args) {	
		DebuggerQueue.addDebug(Main.class.getName(), Level.INFO,"Starting application %s", ApplicationInfo.APP_FULL);	
		downloadReqLibs();
		CheckLogs();
		InitScriptWatch();
		CheckTemplateManager();
		CheckJavaVersion();
		CheckPlugins();
		CheckConfig();
		CheckAppVersion();

		StartMainWindow();
	}

	/**
	 * Create main window
	 */
	private static void StartMainWindow()
	{
		Display.getDefault().syncExec(new Runnable() {

			@Override
			public void run() {
				MainForm mf = new MainForm("MainForm");				
				mf.open();	
			}
		});		
	}

	/**
	 * Check and load default config (settings.xml)
	 */
	private static void CheckConfig()
	{
		Configuration.CheckConfiguration(ApplicationInfo.CFG_SETTINGS);		
		Configuration.loadUSfromFile(ApplicationInfo.CFG_SETTINGS);
		Configuration.loadCSfromFile(ApplicationInfo.CNS_SERVERS);
		Configuration.CheckColorsSettings();
	}

	/**
	 * Check and load plugins
	 */
	private static void CheckPlugins()
	{
		CubePluginsHost.initPlugins(ApplicationInfo.PLG_DEFAULT_DIRECTORY);	
	}

	/**
	 * Enable log 
	 */
	private static void CheckLogs()
	{
		DebuggerQueue.setLoglevel(Level.ALL);
		DebuggerQueue.enableHTMLLog();
	}


	private static void CheckTemplateManager()
	{
		TemplateManager.init();
	}

	private static void CheckJavaVersion() {
		String s = System.getProperty("java.version");
		int version = Integer.parseInt(s.split("[.]")[1]);
		if(version < 6){
			DebuggerQueue.addDebug("main", Level.FATAL, "JRE version out of date. Requires upgrade to full use CubeIRC");
			new AlertBox(new Shell(), "JRE Warning: "+ s, "You are not currently using JRE 1.6.0_27 or higher, CubeIRC may not function properly for you. Please update your Java installation.", SWT.ICON_WARNING);
			System.exit(0);
		}	
	}

	private static void CheckAppVersion()
	{
		//		try
		//		{
		//			Utils.asyncExec(new Shell().getDisplay(), new Runnable() {
		//				
		//				@Override
		//				public void run() {
		//					//TODO: Implement program version update
		DebuggerQueue.addDebug("", Level.INFO,"Checking for application update");
		HTTPClient.sendGetRequest(ApplicationInfo.APP_UPDATE_URL, "");							
		//				}
		//			});
		//			
		//
		//		}
		//		catch (Exception e) {
		//			DebuggerQueue.addDebug(e, Level.WARN, "I can't check CubeIRC version! error: %s",e.getMessage());
		//		}
	}

	private static void InitScriptWatch()
	{					
		setScriptWatch(new ScriptWatcher("ScriptWatcher"));
	}

	private static void downloadReqLibs()
	{
		ApplicationInfo.initReqLibs();
		
		String d_tocheck = System.getProperty("java.library.path").split(";")[0];
		for (Iterator<String> it = ApplicationInfo.LIBS_TODOWNLOAD.keySet().iterator(); it.hasNext();)
		{
			String key = it.next();
			String value = ApplicationInfo.LIBS_TODOWNLOAD.get(key);
			
			File f = new File(d_tocheck + "/" + key);
			if (!f.exists())
			{
				DebuggerQueue.addDebug("Requirement libs", Level.WARN, "Lib %s in %s don't exist, try to download...", key, f.toString());
				try
				{
					HTTPClient.downloadFromUrl(new URL(value), d_tocheck + "\\"+ key, ApplicationInfo.APP_FULL);
					DebuggerQueue.addDebug("Requirement libs", Level.INFO, "Lib %s downloaded!", value );
				}
				catch(Exception ex)
				{
					DebuggerQueue.addDebug("Requirement libs", Level.WARN, "Error during downloading lib %s! Error %s", key, ex.getMessage() );
				}
			}
			else
			{
				DebuggerQueue.addDebug("Requirement libs", Level.WARN, "Lib %s ok, exist!", key, f.toString());
			}
		}
	}

}
